package com.example.pattern.home

import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView

import com.example.pattern.R
import com.example.pattern.data.PictureViewModel
import com.example.pattern.databinding.FragmentHome2Binding
import com.example.pattern.utils.TimeUtils
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream


class HomeFragment : Fragment() {
    private lateinit var binding:com.example.pattern.databinding.FragmentHome2Binding
    private val viewModel:PictureViewModel by activityViewModels()
    private val mAdapter = PictureAdapter()
    private var mUri: Uri? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentHome2Binding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //观察变化
        viewModel.models.observe(viewLifecycleOwner){
            mAdapter.setData(it)
        }
         binding.recyclerView.apply {
             layoutManager = ScaleLayoutManager(requireContext())
             adapter = mAdapter
             PagerSnapHelper().attachToRecyclerView(this)
         }
        binding.ivAdd.setOnClickListener {
            val action = HomeFragmentDirections.actionHomeFragmentToDrawFragment()
            findNavController().navigate(action)
        }
        binding.ivDelete.setOnClickListener {
            val lm = binding.recyclerView.layoutManager as LinearLayoutManager
            val index = lm.findFirstCompletelyVisibleItemPosition()
            viewModel.deletePicture(index)
        }
        binding.ivShare.setOnClickListener {
            val lm = binding.recyclerView.layoutManager as LinearLayoutManager
            val index = lm.findFirstCompletelyVisibleItemPosition()
            val picture = viewModel.models.value!![index]
            share(picture.url)
        }
        binding.ivDown.setOnClickListener {
            val lm = binding.recyclerView.layoutManager as LinearLayoutManager
            val index = lm.findFirstCompletelyVisibleItemPosition()
            val picture = viewModel.models.value!![index]
            downLoad(picture.url)
        }
    }
    fun downLoad(filePath: String){
        val file = File(filePath)
        if (!file.exists()) return
        val uri = if (VERSION.SDK_INT>VERSION_CODES.Q) {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        }else{
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME,TimeUtils.timeName())
            put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg")
        }
        val imageUri = requireActivity().contentResolver.insert(uri,contentValues)
        if(VERSION.SDK_INT>VERSION_CODES.R){
            MediaStore.createWriteRequest(requireActivity().contentResolver, listOf(imageUri))
        }
        requireContext().contentResolver.openOutputStream(imageUri!!).use { os ->
            BufferedInputStream(FileInputStream(file)).use { bis ->
                val bufferArray = ByteArray(1024)
                var len = bis.read(bufferArray,0,1024)
                while (len > 0){
                    os!!.write(bufferArray,0,len)
                    len = bis.read(bufferArray,0,1024)
                }
                os!!.flush()
                Toast.makeText(requireContext(),"保存成功",Toast.LENGTH_LONG).show()
                mUri = imageUri
            }
        }
    }
    fun share(filePath:String){
        val file = File(filePath)
        if(!file.exists())return
        val url = FileProvider.getUriForFile(
            requireContext(),
            "com.example.pattern.fileProvider",
            file
        )
        val intent = Intent(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_STREAM,url)
        intent.type="image/pfg"
        startActivity(Intent.createChooser(intent,"图片分享"))
    }
}